// pages/operation/operation.js
const app = getApp()
const util = require('../../utils/util.js')
Page({
    /**
     * 页面的初始数据
     */
    data: {
        isConnected: true,
        connecting: false,
        temperature: null,
        integer: "--",
        decimal: "",
        routeName: '',
        bloodOxygen: '',
        heartRate: '',
        isZh: app.globalData.isZh,
        baseURL: app.globalData.baseURL,
        deviceId: '',
        serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
        shortServiceId: '0xFFF0',
        characteristicId: '0000FFF1-0000-1000-8000-00805F9B34FB',
        shortCharacteristicId: '0xFFF1',
        UUID: "",
       
    },
    onLoad(options) {
        if (!app.globalData.isZh) {
            wx.setTabBarItem({
                index: 0,
                text: 'Measure'
            })
            wx.setTabBarItem({
                index: 1,
                text: 'My'
            })
        }

        this.setData({
            routeName: wx.getStorageSync('routeName')
        });
        console.log(this.data.routeName);
        console.log(this.data.deviceId);

        this.setData({
            deviceId: wx.getStorageSync('deviceId')
        });
       
        console.log("已绑定的设备", this.data.deviceId)
        if (!this.data.deviceId) {
            return wx.redirectTo({
                url: '../connection/connection'
            });
        }
        console.log(this.data.serviceId);
        wx.getConnectedBluetoothDevices({
            services: [this.data.serviceId],
            success: (res) => {
                console.log("获取已连接设备成功", res);
                // console.log(res);
                if (res.devices.some(device => device.deviceId === this.data.deviceId)) {
                    this.setData({
                        isConnected: true
                    });
                    this.getServiceById(this.data.deviceId);
                    this.watchState();
                } else {
                    this.setData({
                        isConnected: false
                    });
                }
            },
            fail: (res) => {
                console.error("获取已连接设备失败", res);
                this.setData({
                    isConnected: false
                });
            },
        });
    },
    watchState() {
        wx.onBLEConnectionStateChange((res) => {
            // 该方法回调中可以用于处理连接意外断开等异常情况
            // console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`);
            this.setData({
                isConnected: res.connected
            });
            if (!res.connected) {
                wx.showToast({
                    title: this.data.isZh ? '蓝牙已断开' : 'Bluetooth disconnected',
                    icon: "none",
                    mask: true
                })
            }
        });
    },
    getServiceById(deviceId) {
        wx.getBLEDeviceServices({
            deviceId,
            success: (res) => {
                console.log("服务列表", res)
                for (let i = 0; i < res.services.length; i++) {
                    if (res.services[i].isPrimary && res.services[i].uuid.toUpperCase() === this.data.serviceId) {
                        // 可根据具体业务需要，选择一个主服务进行通信
                        return this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
                    }
                }
            },
            fail: (res) => {
                console.error("获取服务列表失败", res);
                this.reconnect();
            }
        })
    },
    getBLEDeviceCharacteristics(deviceId, serviceId) {
        wx.getBLEDeviceCharacteristics({
            deviceId,
            serviceId,
            success: (res) => {
                console.log('特征列表', res)
                for (let i = 0; i < res.characteristics.length; i++) {
                    let item = res.characteristics[i]
                    console.log(item);
                    console.log(item.uuid.toUpperCase());
                    console.log(this.data.characteristicId);
                    console.log(item.properties.read);
                  
                    if (item.properties.notify && item.uuid.toUpperCase() === this.data.characteristicId) {
                        console.log("目标特征", item)
                        wx.notifyBLECharacteristicValueChange({
                            deviceId,
                            serviceId,
                            characteristicId: item.uuid,
                            type: "notification",
                            state: true,
                            success: (res) => {
                                console.log('读取设备数据', res);
                                this.parseData(res);
                            }
                        })
                    }
                    // || item.properties.indicate
                    if (item.properties.notify) {
                        // 必须先启用 wx.notifyBLECharacteristicValueChange 才能监听到设备 onBLECharacteristicValueChange 事件
                        wx.notifyBLECharacteristicValueChange({
                            deviceId,
                            serviceId,
                            characteristicId: item.uuid,
                            state: true,
                            type: "notification",
                            success: function (e) {
                                console.log('success: ' + JSON.stringify(e));
                                // 操作之前先监听，保证第一时间获取数据
                            },
                            fail: function (e) {
                                console.log('error: ' + JSON.stringify(e));
                            }
                        })
                    }
                }
            },
            fail: (res) => {
                console.error('获取特征列表失败', res)
            }
        })
        // 操作之前先监听，保证第一时间获取数据
        wx.onBLECharacteristicValueChange((res) => {
            console.log('监控设备数据', res);
            console.log(res.value);
            this.parseData(res);
        });
    },
    parseData(result) {
        let hexStr = util.ab2hex(result.value);
        console.log(result.value);

        let val = "";
        let len = hexStr.length / 2;;
        if (this.data.routeName == "血氧") {
            this.data.bloodOxygen = parseInt(hexStr.substr(1 * 2, 2), 16)
            this.data.heartRate = parseInt(hexStr.substr(3 * 2, 2), 16)
        } else if (this.data.routeName == "体温") {
            for (let i = 0; i < len; i++) {
                console.log(parseInt(hexStr.substr(i * 2, 2), 16));
                console.log(parseInt(hexStr.substr(i * 2, 2)));
                val += String.fromCharCode(parseInt(hexStr.substr(i * 2, 2), 16));
            }
        }


        console.log("解析到的数据", val);
        val = val.trim();
        this.setData({
            temperature: parseFloat(val.split(":")[1])
        });
        console.log(this.data.temperature);
        if (!isNaN(this.data.temperature)) {
            const [integer, decimal] = this.data.temperature.toFixed(1).split('.');
            this.setData({
                integer,
                decimal
            });
        } else {
            this.setData({
                integer: val.toUpperCase().includes('L') ? 'Low' : val.toUpperCase().includes('H') ? 'High' : '--',
                decimal: ""
            });
        }
    },
    reconnect() {
        if (this.data.connecting || this.data.isConnected) {
            return;
        }
        this.setData({
            connecting: true
        });
        // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.bluetooth" 这个 scope
        wx.getSetting({
            success: (res) => {
                // console.log("蓝牙权限", res.authSetting['scope.bluetooth'])
                // (1) 微信授权已关闭，弹窗打开
                if (res.authSetting['scope.bluetooth'] != undefined && res.authSetting['scope.bluetooth'] == false) {
                    wx.showToast({
                        title: this.data.isZh ? '请授权' : 'Please authorize',
                        icon: "none",
                        mask: true
                    })
                    wx.openSetting({
                        success: (authData) => {
                            if (authData.authSetting['scope.bluetooth'] == true) {
                                // wx.showToast({ title: this.data.isZh ? '授权成功' : 'Authorized', icon: "success", mask: true })
                                this.openBluetooth(); // 打开蓝牙适配器 
                            } else {
                                wx.showToast({
                                    title: this.data.isZh ? '授权失败' : 'Unauthorized',
                                    icon: "error",
                                    mask: true
                                });
                                this.setData({
                                    connecting: false,
                                    isConnected: false
                                });;
                            }
                        }
                    })
                }
                // (2) 'scope.bluetooth'属性不存在，需要授权
                if (res.authSetting['scope.bluetooth'] == undefined) {
                    wx.authorize({
                        scope: 'scope.bluetooth',
                        success: (res) => {
                            this.openBluetooth(); // 打开蓝牙适配器 
                        }
                    })
                }
                // (3) 已经授权
                if (res.authSetting['scope.bluetooth'] == true) {
                    this.openBluetooth(); // 打开蓝牙适配器 
                }
            },
            fail: () => {
                wx.showToast({
                    title: this.data.isZh ? "请检查网络连接" : "Network Error",
                    icon: "error",
                    mask: true
                });
            }
        })
        // setTimeout(() => {
        //     this.setData({ connecting: false, isConnected: true, temperature: 36.5, integer: 36, decimal: 5 });
        // }, 3000);
    },
    openBluetooth() {
        this.setData({
            connecting: true
        });
        // 打开蓝牙适配器
        wx.openBluetoothAdapter({
            success: (res) => {
                // console.log("打开蓝牙适配器成功：", res);
                this.connectById(this.data.deviceId);
            },
            fail: (res) => {
                console.error("打开蓝牙适配器失败：", res);
                wx.showToast({
                    title: this.data.isZh ? "请确认手机蓝牙已开启并授权微信" : "Make sure that Bluetooth is turned on and allow Wechat to access",
                    icon: 'none',
                    mask: true
                });
                this.setData({
                    connecting: false,
                    isConnected: false
                });
            }
        });
    },
    connectById(deviceId) {
        wx.createBLEConnection({
            deviceId, // 搜索到设备的 deviceId
            success: (res) => {
                // console.log("重连成功", res)
                this.setData({
                    connecting: false,
                    isConnected: true
                });
                this.getServiceById(this.data.deviceId);
                this.watchState();
            },
            fail: (res) => {
                console.error("重连失败", res)
                wx.showToast({
                    title: this.data.isZh ? "蓝牙连接失败" : "Bluetooth connection failed",
                    icon: 'none',
                    mask: true
                });
                this.setData({
                    connecting: false,
                    isConnected: false
                });
            }
        });
    },
    upload() {
        this.setData({
            UUID: util.genID()
        })
        const time = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0, 8)
        const Data = [{
            "ExamId": this.data.UUID,
            "ExamModel": {
                "SMACHINECODE": "",
                "CHECKDOCTOR": "",
                "CHECKDATE": time,
                "UPDATED_DATE": time,
                "ARCHIVEID": wx.getStorageSync('identityno'),
                "created_UserId": "",
                "CREATED_DATE": time,
                "CREATED_BY": "小文",
                "SSUPPLIERCODE": "",
                "updated_UserId": "",
                "UPDATED_BY": "小文",
                "CARDNO": wx.getStorageSync('identityno'),
                "DUNS": "贝莱福",
                "ID": this.data.UUID,
                "DATARESTYPE": "",
                "ISSUCCESS": ""
            },
            "ExamItems": [{
                "Temperature": {
                    "ISUPLOADSUCCESS": 0,
                    "SMACHINECODE": "",
                    "Phone": "",
                    // "PULSE": this.data.heartRate,
                    "TEMPERATURE":this.data.temperature,
                    "UPDATED_DATE": time,
                    "CardNo": wx.getStorageSync('identityno'),
                    "Name": "",
                    "CREATED_DATE": time,
                    "CREATED_BY": "小文",
                    "SSUPPLIERCODE": "",
                    "UPDATED_BY": "小文",
                    "archiveId": wx.getStorageSync('identityno'),
                    "DUNS": "贝莱福",
                    "EXAMID": this.data.UUID,
                    "DATARESTYPE": "",
                    // "OXYGEN": this.data.bloodOxygen,
                    "ISSUCCESS": ""
                }
            }]
        }];
        let myjsonData = JSON.stringify(Data);
        wx.showToast({
            title: this.data.isZh ? "上传中" : "Uploading",
            icon: "loading",
            mask: true
        });
        wx.request({
            url: app.globalData.baseURL + "/ChoiceMMed/Api/Data/Upload",
            data: {
                accessTokenKey: "002dbfd9ef2f4092a857cbfad39df1c7",
                Data: myjsonData
            },
            method: "POST",
            header: {
                // 'content-type': 'application/json' // 默认值
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
            },
            success: ({
                data
            }) => {
                console.log(data);
                if (data.Code != 0) {
                    wx.showToast({
                        title: this.data.isZh ? "上传失败" : "Failed",
                        icon: "error",
                        mask: true
                    });
                } else {
                    wx.showToast({
                        title: this.data.isZh ? "上传成功" : "Success",
                        icon: "success",
                        mask: true
                    });
                }
            },
            fail: (res) => {
                console.error("上传失败", res);
                wx.showToast({
                    title: this.data.isZh ? "请检查网络连接" : "Network Error",
                    icon: "error",
                    mask: true
                });
            }
        });
    },
    unbind() {
        wx.showModal({
            title: app.globalData.isZh ? '提示' : 'Wraning',
            content: app.globalData.isZh ? '是否确认解绑设备？' : "Are you sure?",
            confirmText: app.globalData.isZh ? '确认' : "Yes",
            cancelText: app.globalData.isZh ? '取消' : "No",
            success(res) {
                console.log(res.confirm);
                console.log(wx.getStorageSync('deviceId'));
                if (res.confirm) {
                    wx.closeBLEConnection({
                        deviceId: wx.getStorageSync('deviceId'),
                        success: (res) => {
                            // console.log('蓝牙断开成功', res) 
                        },
                        fail: (res) => {
                            console.error('蓝牙断开失败', res)
                        }
                    });
                    wx.closeBluetoothAdapter();
                    wx.showToast({
                        title: app.globalData.isZh ? "已解绑" : "Done",
                        icon: "success",
                        mask: true
                    });
                    wx.removeStorageSync('deviceId');
                    setTimeout(wx.switchTab, 1000, {
                        url: '../switchpage/switchpage'
                    });
                }
            }
        });
    },
})